package com.kuangstudy.controller.set;

import com.kuangstudy.service.set.RandomService;
import com.kuangstudy.vo.R;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 飞哥
 * @Title: 学相伴出品
 * @Description: 我们有一个学习网站：https://www.kuangstudy.com
 * @date 2021/5/23 17:41
 */
@RestController
@Log4j2
public class RandomController {

    @Autowired
    private RedisTemplate redisTemplate;

    // 1 : 初始化抽奖的信息
    @GetMapping("/random/card")
    public R randomData() {
        try {
            String result = null;
            // 1: 随机从集合中获取一个元素出来
            String randomMember = (String) this.redisTemplate.opsForSet().randomMember(RandomService.RANDOM_SET_KEY);
            if (!StringUtils.isEmpty(randomMember)) {
                int splitIndex = randomMember.indexOf("#");
                int coin = Integer.valueOf(randomMember.substring(0, splitIndex));
                if (coin == 0) {
                    result = "谢谢你的参与";
                } else if (coin == 10) {
                    result = "获取10个K币";
                } else if (coin == 50) {
                    result = "获取50个K币";
                } else if (coin == 100) {
                    result = "获取100个K币";
                } else {
                    result = "谢谢你的参与";
                }


                if (coin > 0) {
                    // 抽取成功以后同步到数据库db中
                }
                return R.ok().data("message", result).data("coin", coin);
            }
            return R.error().message("抽奖已经过期");
        } catch (Exception ex) {
            log.error("抽奖失败");
            return R.error().message("服务忙!!!");
        }
    }

}
